/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servidorped;

import commands.Command;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Micosil
 */
class CommandProcessor {

    private final String direccionDeLosComandos = "./build/classes/Commands";
    private URLClassLoader classLoader = null;

    CommandProcessor() {
        if (classLoader == null) {
            try {
                classLoader = URLClassLoader.newInstance(new URL[]{new File(direccionDeLosComandos).toURI().toURL()});
            } catch (MalformedURLException ex) {
                Logger.getGlobal().log(Level.SEVERE, "The programmer sucks!", ex);
            }
        }
    }

    public void process(String readln, User user) {
        //Formato esperado: /Comando, parametro, parametro, parametro
        //Las comas del formato original vienen escapadas, pero creo que es muy irrelevante.
        String[] tokenList = readln.trim().split("[^/],");
        for (int i = 0; i < tokenList.length; i++) {
            tokenList[i] = tokenList[i].replaceAll("/,", ",");
        }
        tokenList[0] = tokenList[0].substring(1);
        if (user.getUserName() == null) {
            if (!(tokenList[0].equals("register") || tokenList[0].equals("login"))) {
                user.getUserSender().setToSend("Command not authorized for unidentified users.");
                return;
            }
        }
        if ((tokenList[0].startsWith("admin")) && !(user.isAdmin())){
            user.getUserSender().setToSend("Command " + tokenList[0] + " does not exist.");
            Logger.getGlobal().log(Level.INFO, "Unauthorized user {0} attemted to use admin command {1}", new Object[]{user.getUserName(), tokenList[0]});
            return;
        }

        try {
            ((Command) Class.forName("Commands." + tokenList[0], true, classLoader).newInstance()).execute(tokenList, user);
        } catch (ClassNotFoundException ex) {
            Logger.getGlobal().log(Level.INFO, "User {0} requested unexisting command {1}", new Object[]{user.getUserName(), tokenList[0]});
            user.getUserSender().setToSend("Command " + tokenList[0] + " does not exist.");
        } catch (IllegalAccessException | InstantiationException ex) {
            Logger.getGlobal().log(Level.SEVERE, "Could not initiate process of request {0}", tokenList[0]);
        }
    }
}
